<template>
  <div class="table-box">
    <ProTable ref="proTable" title="用户列表" :columns="columns" :requestApi="articleApi.myArticle" :searchCol="5">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="proTable?.element?.toggleAllSelection"
          >全选 / 全不选</el-button
        >
        <el-button type="success" plain :disabled="!scope.isSelected" @click="changeListStatus(true)"
          >批量启用</el-button
        >
        <el-button type="danger" plain :disabled="!scope.isSelected" @click="changeListStatus(false)"
          >批量禁用</el-button
        >
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link @click="detailArticle(scope.row)">预览</el-button>
        <el-button type="success" link @click="editArticle(scope.row)">编辑</el-button>
        <el-button type="danger" link @click="deleteArticle(scope.row)">删除</el-button>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="complexProTable">
import articleApi from '@/apis/article';
import categoryApi from '@/apis/category';
import type { ArticleApiType } from '@/apis/article/namespace';
import type { ColumnProps, ProTableInstance } from '@/components/proTable/interface';
import { RouterEnum } from '@/enum';
import { dateZhFormat } from '@/utils/common';
import { CirclePlus, Picture } from '@element-plus/icons-vue';

// 路由
const router = useRouter();

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns = reactive<ColumnProps<ArticleApiType.Article>[]>([
  { type: 'selection', width: 50 },
  { prop: 'id', label: '文章ID', width: 80 },
  {
    prop: 'preview',
    label: '文章封面',
    width: 90,
    align: 'center',
    render: (scope) => {
      return (
        <error-img class="text-[2rem]" src={scope.row.preview} fit="cover" preview-src-list={[scope.row.preview]} />
      );
    },
  },
  { prop: 'title', label: '文章标题', width: 200, search: { el: 'input' } },
  {
    prop: 'categoryName',
    label: '文章栏目',
    width: 200,
    enum: categoryApi.list,
    fieldNames: { label: 'title', value: 'title' },
    search: { el: 'select' },
    render(scope) {
      return <el-tag type="success">{scope.row?.category?.title}</el-tag>;
    },
  },
  {
    prop: 'createAt',
    label: '创建时间',
    width: 200,
    render: (scope) => {
      return <div class="text-gray-500">{dateZhFormat(scope.row?.createAt ?? '')}</div>;
    },
  },
  {
    prop: 'updateAt',
    label: '更新时间',
    width: 200,
    render(scope) {
      return <div class="text-gray-500">{dateZhFormat(scope.row?.updateAt ?? '')}</div>;
    },
  },
  {
    prop: 'status',
    label: '文章状态',
    width: 200,
    fixed: 'right',
    render: (scope) => {
      return (
        <el-switch
          model-value={scope.row.status}
          active-text={scope.row.status ? '启用' : '禁用'}
          active-value={true}
          inactive-value={false}
          onClick={() => changeStatus(scope.row)}
        />
      );
    },
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 200 },
]);

// 批量启用/禁用
const changeListStatus = (status: boolean) => {
  ElMessageBox.confirm(`确认${status ? '启用' : '禁用'}所选文章吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const list = proTable.value?.selectedList ?? [];
    const ids = list.map((item) => item.id);
    await articleApi.changeStatus({ ids, status });
    proTable.value?.search();
  });
};

// 更改文章状态
const changeStatus = async (row: ArticleApiType.Article) => {
  ElMessageBox.confirm(`确认${row.status ? '禁用' : '启用'}该文章吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await articleApi.changeStatus({ ids: [row.id ?? ''], status: !row.status });
    proTable.value?.search();
  });
};

// 查看文章详情
const detailArticle = (row: ArticleApiType.Article) => {
  router.push({ name: RouterEnum.ARTICLE_DETAIL, query: { articleId: row.id } });
};

// 编辑文章
const editArticle = (row: ArticleApiType.Article) => {
  router.push({ name: RouterEnum.ARTICLE_WRITE, query: { articleId: row.id } });
};

// 删除文章
const deleteArticle = (row: ArticleApiType.Article) => {
  const params = { ids: [row.id ?? ''] };
  ElMessageBox.confirm('确认删除该文章吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await articleApi.delete(params);
    proTable.value?.search();
  });
};
</script>
